package top.jingles.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogWriter {
    
    Writer INFO;

    Writer ERROR;

    public void initLogWriters(String logFilePath, String errorlogFilePath) {
        initInfoWriter(logFilePath);
        initErrorWriter(errorlogFilePath);
    }

    public void close() {
        try {
            INFO.close();
            ERROR.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void initInfoWriter(String logFilePath) {
        Writer info = null;
        try {
            info = new OutputStreamWriter(new FileOutputStream(logFilePath, true), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
        INFO = info;
    }

    void initErrorWriter(String errorlogFilePath) {
        Writer err = null;
        try {
            err = new OutputStreamWriter(new FileOutputStream(errorlogFilePath, true), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
        ERROR = err;
    }

    String nowString() {
        return nowString("yyyy-MM-dd HH:mm:ss");
    }

    String nowString(String formatStr) {
        SimpleDateFormat df = new SimpleDateFormat(formatStr);  //设置日期格式
        return df.format(new Date());   // new Date()为获取当前系统时间
    }

    public void info(String msg) {
        try {
            System.out.println(msg);
            INFO.write(nowString() + "\t" + msg + "\n");
            INFO.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void error(String msg) {
        try {
            System.err.println(msg);
            ERROR.write(nowString() + "\t" + msg + "\n");
            ERROR.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}